package com.news.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.news.common.lang.Const;
import com.news.common.lang.Result;
import com.news.entity.SysUser;
import com.news.service.SysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Leeion
 * @since 2021-12-06
 */
@RestController
//事务回滚注解
@Transactional
@RequestMapping("/sys/user")
public class SysUserController extends BaseController{

    //按uid回显
    @GetMapping("/info/{uid}")
    public Result info(@PathVariable(name = "uid") Long uid){

        return Result.succ(sysUserService.getById(uid));
    }

    //分页显示文章内容接口
    @GetMapping("/list")
    public Result list(String username){

        Page<SysUser> page = sysUserService.page(getPage(), new QueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username),"username",username));//查询用户
        return Result.succ(page);
    }

    //新增用户接口
    @PostMapping("/save")
    public Result saveUser(@Validated @RequestBody SysUser sysUser){
        if(sysUser.getUsername() != null){
            return Result.fail("该用户名已存在");
        }
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setUpdateTime(LocalDateTime.now());
        sysUser.setAvatar(Const.DEFULT_AVATAR);
        sysUser.setPassword(SecureUtil.md5(Const.PASSWORD+Const.SALT));
        sysUserService.save(sysUser);
        return Result.succ(sysUser);
    }

    //用户删除接口
    @PostMapping("/delete")
    public  Result delete(@RequestBody Long[] ids){
        //单个删除和批量删除
        sysUserService.removeByIds(Arrays.asList(ids));
        return Result.succ("");
    }

    //更新用户接口
    @PostMapping("/update")
    public Result update(@Validated @RequestBody SysUser sysUser){

        sysUser.setUpdateTime(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        return Result.succ(sysUser);
    }

    //重置密码
    @PostMapping("/repass")
    public Result repass(@RequestBody Long uid){
        //获取用户uid
        SysUser sysUser = sysUserService.getById(uid);
        sysUser.setPassword(SecureUtil.md5(Const.PASSWORD+Const.SALT));
        sysUser.setUpdateTime(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        return Result.succ("");
    }

}
